<template>
  <div id="login">
    <div class="form-wrap">
      <ul class="menu-tab">
        <!-- current表示的是选中的状态 -->
        <!-- <li class="current">登录</li>
        <li>注册</li> -->
        <li v-for="item in data.tab_menu" :class="{'current': data.current_menu === item.type}" :key="item.type" @click="data.current_menu = item.type">{{item.label}}</li>
      </ul>
      <el-form ref="account_form" :model="data.form" :rules="data.form_rules">
        <el-form-item prop="username">
          <label class="form-label">用户名</label>
          <el-input v-model="data.form.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <label class="form-label">密码</label>
          <el-input type="password" v-model="data.form.password"></el-input>
        </el-form-item>
        <el-form-item v-if="data.current_menu === 'register'" prop="passwords">
          <label class="form-label">确认密码</label>
          <el-input type="password" v-model="data.form.passwords"></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <label class="form-label">验证码</label>
          <el-row :gutter="10">
            <el-col :span="14">
              <el-input v-model="data.form.code"></el-input>
            </el-col>
            <el-col :span="10">
              <el-button type="primary" class="el-button-block" @click="handlerGetCode" :disabled="data.code_button_disabled" :loading="data.code_button_loading">{{ data.code_button_text }}</el-button>
            </el-col>
          </el-row> 
        </el-form-item>
        <el-form-item>
          <el-button type="success" :disabled="data.submit_button_disabled" :loading="data.submit_button_loading" class="el-button-block" @click="submitForm">{{ data.current_menu === 'login' ? '登录' : '注册' }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <test @my-events="doSomeThing" v-model:title="bookTitle" v-model:name="fileName" @change="changeName"/>
    <div>{{bookTitle}}</div>
  </div>
</template>
<script>
import { reactive, ref, resetTracking, toRefs } from '@vue/reactivity';
import { useStore } from 'vuex';
import { useRouter, useRoute } from 'vue-router';
// 引入校验的事件
import { validate_email, validate_password, validate_code } from '@/utils/validate'
import { getCurrentInstance, onBeforeMount } from 'vue';
import { getCode, ErrorHttp } from "@/api/common";
import { Register, Login } from "@/api/account";
import test from "@/views/test/parent-component.vue"
import sha1 from 'js-sha1';
export default {
  name: 'Login',
  emits: {
    myEvents: payload => {
      console.log(payload + 'emits里打印的')
    }
  },
  components: {
    test
  },
  props: {
    bookTitle: {
      type: String,
      defalut: '小王子'
    },
    fileName:{
      type: String,
      defalut: '小牛子'
    }
  },
  setup(props, { emit, }) {
    console.log(useRouter(), useRoute(), "useRouter和useRoute")
    // emit('myEvents')
    // 设置名称的校验规则
    const validate_name_rules = (rule, value, callback) => {
      let regEmail = validate_email(value); // 通过utils封装检测时方法返回的内容
      if (value == '') {
        callback(new Error('请输入邮箱'));
      } else if (!regEmail) {
        callback(new Error('邮箱格式不正确'));
      } else {
        callback();
      }
    }
    // 密码校验
    const validate_password_rules = (rule, value, callback) => {
      let regPassword = validate_password(value);
      // 获取确认密码的内容
      const passwordsValue = data.form.passwords;
      if (value === '') {
        callback(new Error("请输入密码"));
      } else if (!regPassword) {
        callback(new Error("请输入>=6并且<=20位的密码,包含数字、字母"));
      } else {
        callback();
      }
    }
    // 确认密码校验
    const validate_passwords_rules = (rule, value, callback) => {
      // 如果时登录,不需要校验确认密码,默认通过就可以
      if (data.current_menu === 'login') {
        callback();
      }
      let regPassword = validate_password(value);
      // 获取密码
      const passwordValue = data.form.password;
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (passwordValue && passwordValue !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    }
    // 验证码进行校验
    const validate_code_rules = (rule, value, callback) => {
      let regCode = validate_code(value);
      // data.submit_button_disabled = !regCode;  // 验证码格式校验后激活按钮
      if (value === '') {
        callback(new Error("请输入验证码"));
      } else if (!regCode) {
        callback(new Error("请输入6位的验证码"));
      } else {
        callback();
      }
    }
    // 定义数据
    const data = reactive({
      form: {
        username: '', // 用户名
        password: '', // 密码
        passwords: '', // 确认密码
        code: '', // 验证码
      },
      tab_menu: [
        { type: 'login', label: '登录' },
        { type: 'register', label: '注册' }
      ],
      current_menu: 'login',
      code_button_disabled: false, // 启用按钮
      code_button_loading: false, // 加载状态
      code_button_text: '获取验证码', // 按钮的文字
      code_button_timer: null,
      submit_button_disabled: true, // 提交按钮
      form_rules: {
        username: [
          { required: true, message: '请输入邮箱地址', trigger: 'change' },
          // { min: 3, max: 5, message: '长度在3到5个字符', trigger: 'change' },
          { validator: validate_name_rules, trigger: ['change', 'blur'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { validator: validate_password_rules, trigger: ['blur', 'change'] }
        ],
        passwords: [
          { required: true, message: '请再次输入密码', trigger: 'change' },
          { validator: validate_passwords_rules, trigger: ["blur", "change"]}
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'change' },
          { validator: validate_code_rules, trigger: ["blur", "change"]}
        ]
      },
    })
    const doSomeThing = (payload) => {
      console.log('WO SHI DO doSomeThing' + payload)
    }
    const changeName = (paylod) => {
      console.log(payload + '99999')
    }

    // ctx 对象
    const instance = getCurrentInstance();
    const { ctx, proxy } = getCurrentInstance();
    console.log(instance);
    console.log(ctx) 
    console.log(proxy) 

    // // 切换高亮
    const toggleMenu = ((type) => {
      current_menu.value = type;
    })
    // 获取验证码
    const handlerGetCode = () => {
		const username = data.form.username;
		const password = data.form.password;
		const passwords = data.form.passwords;
		// 校验用户名
		if (!validate_email(username)) {
			ElMessage.error({
				message: '用户名不能为空或格式不正确',
				type: 'error'
			})
			return false;
		}
		// 校验密码
		if (!validate_password(password)) {
			ElMessage({
				message: '密码不能为空或格式不正确',
				type: 'error'
			})
			return false;
		}
		// 判断非登录时，校验两次密码
		if (data.current_menu === 'register' && (password !== passwords)) {
			ElMessage({
				message: '两次的密码不一致',
				type: 'error'
			})
			return false;
		}
		// 获取验证码的接口
    const requestData = {
      username: data.form.username,
      module: data.current_menu
    }
    data.code_button_loading = true;
    data.code_button_text = '发送中';
    data.submit_button_disabled = false; // 可以放到校验里面  也可以在接口请求完成后,但目前在接口后是没有办法实现

		getCode(requestData).then(response => {
      console.log(response.data)
      const data = response.data;
      if (data.resCode === 1024) {
        ElMessage({
          message: data.message,
          type: 'error'
        })
        // 执行倒计时
        countdown();
        return false;
      }
    }).catch(error => {
      data.code_button_loading = false;
      data.code_button_text = '获取验证码';
    })
    ErrorHttp(requestData).then(response => {
      // 获取后端返回的数据
      const resData = response.data;
      // elementui提示
      ElMessage({
        message: resData.message,
        type: 'success'
      })
    }).catch(error => {
      data.code_button_loading = false;
      data.code_button_text = '获取验证码'
    })
      }

      // 倒计时
      const countdown = (time) => {
        let second = time || 60; // 默认时间
        data.code_button_loading = false; // 取消加载
        data.code_button_disabled = true; // 禁止按钮
        data.code_button_text = `倒计时${second}秒`; // 按钮文本
        // 首先判断倒计时是否存在  存在先删除
        if (data.code_button_timer) {
          clearInterval(data.code_button_timer)
        };
        // 开启定时器
        data.code_button_timer = setInterval(() => {
          second--;
          data.code_button_text = `倒计时${second}秒`; // 按钮的文本
          if (second <= 0) {
            data.code_button_disabled = false; // 禁止点击为否定
            data.code_button_text = '重新获取';
            clearInterval(data.code_button_timer)
          }
        }, 1000)
      }
      // 提交表单
      const submitForm = () => {
        proxy.$refs.account_form.validate((valid) => {
          if (valid) {
            data.current_menu === 'login' ? login() : register();
            alert('submit')
          } else {
            alert('表单校验不通过');
            return false;
          }
        })
      }
      // 注册
      const register = () => {
        const requestData = {
          username: data.form.username,
          password: sha1(data.form.password), // 密码进行转义(加密),用到了sha1这个库，可以用的还有base64,md5
          code: data.form.code
        }
        data.submit_button_loading = true; // 要发送的时候显示loading图
        Register(requestData).then(response => {
          ElMessage({
            message: response.message,
            type: 'success'
          })
          // 重置元素
          reset()
        }).catch(error => {
          data.submit_button_loading = false;
        })
      }
      // 重置
      const reset = () => {
        // 重置表单 resetFields是组件自身重置表单的方法  直接调用即可
        proxy.$refs.account_form.resetFields();
        // 切回登录状态
        data.current_menu = 'login';
        // 判断是否存在定时器,有的话进行删除   ##这个的写法是什么##
        data.code_button_timer && clearInterval(data.code_button_timer);
        // 获取验证码重置文本
        data.code_button_text = '获取验证码';
        // 获取验证码激活
        data.code_button_disabled = false;
        // 禁用‘提交’按钮
        data.submit_button_disabled = true;
        // 取消提交按钮的加载
        data.submit_button_loading = false;
      }
      // 通过ref获取html元素
      // const account_form = ref(null);
      // const submitForm = (formName) => {
      //   account_form.value.validate((valid) => {
      //     if (valid) {
      //       alert('submit')
      //     } else {
      //       alert('表单校验不通过');
      //       return false;
      //     }
      //   })
      // }
      // 登录
      const { dispatch, commit } = useStore();
          // 定义一个路由
    console.log(useRouter(), "打印的router")
    // console.log(useRoute(), "打印的router")

    const { push } = useRouter();
      console.log("打印的useStore的值", useStore());

      const login = () => {
        const requestData = {
          username: data.form.username,
          password: sha1(data.form.password),
          code: data.form.code
        }
        data.submit_button_loading = true;
        dispatch("app/loginAction", requestData).then(response => {
          ElMessage({
            message: response.message,
            type: 'success'
          });
          commit("app/SET_TOKEN", response.data.token);
          commit("app/SET_USERNAME", response.data.username);
          
          push({
            path: "/layout"
          })
          reset();
        }).catch(error => {
          data.submit_button_loading = false;
        })
        // Login(requestData).then(response => {
        //   ElMessage({
        //     message: response.message,
        //     type: 'success'
        //   })
        //   reset();
        // }).catch(error => {
        //   data.submit_button_loading = false;
        // })
      }
      // 销毁组件之前---生命周期
      onBeforeMount(() => {
        clearInterval(data.code_button_timer); // 删除倒计时
      })
    return {
      data,
      toggleMenu,
      getCode,
      doSomeThing,
      changeName,
      handlerGetCode,
      submitForm,
      login
    }



    // const data = reactive({
    //   tab_menu: [
    //     { type: 'login', label: '登录' },
    //     { type: 'register', label: '注册' }
    //   ]
    // })

    // let current_menu = ref(data.tab_menu[0].type)
    // // 切换高亮
    // const toggleMenu = ((type) => {
    //   current_menu.value = type;
    // })

    // 定义form的内容
    // const form = reactive({
    //   item: {
    //     username: '', // 用户名
    //     password: '', // 密码
    //     passwords: '', // 确认密码
    //     code: '', // 验证码
    //   }
    // })

    // 使用toRefs之后的写法
    // const data = reactive({
    //   username: '', // 用户名
    //   password: '', // 密码
    //   passwords: '', // 确认密码
    //   code: '999999', // 验证码
    //   tab_menu: [
    //     { type: 'login', label: '登录' },
    //     { type: 'register', label: '注册' },
    //   ],
    //   current_menu: 'login'
    // })
    // const dataItem = toRefs(data);
    // return { data, current_menu, toggleMenu, form }
    // return { 
    //   // ...toRefs(data), // 或者可以返回...toRefs(dataItem)
    //   ...dataItem,
    //   toggleMenu
    // }
  },
  methods: {

  },
}
</script>
<style scoped lang="scss">
#login { 
  height: 100vh; // 设置高度居于浏览器可视高度区域
  background-color: #344a5f;
}
.form-wrap {
  width: 320px;  // 设置宽度
  padding-top: 100px;   // 设置顶部间距
  margin: auto;   // 设置使块元素居中
  background-color: #555321;
}
.menu-tab {
  text-align: center;
  li {
    display: inline-block;
    padding: 10px 24px;
    margin: 0px 10px;
    color: #fff;
    font-size: 14px;
    border-radius: 5px;
    cursor: pointer;
    &.current {
      background-color: rgba(0,0,0,.1); // 选中时候的背景的状态
    }
  }
}
.form-label {
  display: block;
  color: #fff;
  font-size: 14px;
}
</style>